<template>
  <div class="title-bar" data-tauri-drag-region>
    <!-- 左侧占位区域 -->
    <div class="left-section"></div>

    <!-- 中央搜索框 -->
    <div class="search-container" v-if="showSearch">
      <div class="search-wrapper">
        <input 
          type="text" 
          class="search-input" 
          placeholder="搜索..."
          v-model="searchQuery"
          @input="handleSearchInput"
          @keyup.enter="handleSearchSubmit"
        />
        <div class="search-icon">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <circle cx="11" cy="11" r="8"></circle>
            <path d="m21 21-4.35-4.35"></path>
          </svg>
        </div>
      </div>
    </div>

    <!-- 右侧控制区域 -->
    <div class="right-section">
      <!-- 主题切换按钮 -->
      <div class="theme-toggle-container" v-if="isLoggedIn">
        <ThemeToggle :size="'small'" />
      </div>
      
      <!-- 用户头像和下拉菜单 -->
      <div class="user-section" v-if="isLoggedIn">
        <div class="user-avatar" @click="toggleDropdown" title="用户菜单">
          <div class="avatar-circle">
            <span class="avatar-text">{{ userInitial }}</span>
          </div>
          <div class="dropdown-menu" v-if="showDropdown">
            <div class="dropdown-item" @click="openSettings">
              <span class="dropdown-icon">⚙️</span>
              设置
            </div>
            <div class="dropdown-item" @click="handleLogout">
              <span class="dropdown-icon">🚪</span>
              退出登录
            </div>
          </div>
        </div>
      </div>

      <!-- 分割线 -->
      <div class="divider" v-if="isLoggedIn"></div>

      <div class="window-controls">
        <button class="control-btn minimize" @click="minimize" title="最小化">
          <svg width="12" height="12" viewBox="0 0 12 12">
            <rect x="1" y="8" width="10" height="1" fill="currentColor" />
          </svg>
        </button>

        <button class="control-btn maximize" @click="maximize" title="最大化">
          <svg width="12" height="12" viewBox="0 0 12 12">
            <rect x="1.5" y="1.5" width="9" height="9" fill="none" stroke="currentColor" stroke-width="1" />
          </svg>
        </button>

        <button class="control-btn close" @click="close" title="关闭">
          <svg width="12" height="12" viewBox="0 0 12 12">
            <path d="M3 3L9 9M9 3L3 9" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
          </svg>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useAuth } from '../composables/useAuth'
import ThemeToggle from './ThemeToggle.vue'

// 使用 useAuth composable 直接获取登录状态
const { logout, isLoggedIn, currentUser } = useAuth()

// 窗口控制
let appWindow: any = null

const getAppWindow = async () => {
  if (!appWindow) {
    try {
      const { getCurrentWindow } = await import('@tauri-apps/api/window')
      appWindow = getCurrentWindow()
    } catch (error: any) {
      console.log('窗口控制功能在Web环境中不可用')
      return null
    }
  }
  return appWindow
}

const minimize = async () => {
  const aw = await getAppWindow()
  if (aw) await aw.minimize()
}

const maximize = async () => {
  const aw = await getAppWindow()
  if (aw) {
    const isMaximized = await aw.isMaximized()
    if (isMaximized) {
      await aw.unmaximize()
    } else {
      await aw.maximize()
    }
  }
}

const close = async () => {
  const aw = await getAppWindow()
  if (aw) await aw.close()
}

// 用户状态
const currentUserName = computed(() => {
  if (!currentUser.value) return '用户';
  return typeof currentUser.value === 'object' ? currentUser.value.username : currentUser.value;
})
const showDropdown = ref(false)
// 计算用户首字母
const userInitial = computed(() => {
  return currentUserName.value.charAt(0).toUpperCase()
})



// 搜索相关
const searchQuery = ref('')
const showSearch = ref(false)
let searchTimeout: ReturnType<typeof setTimeout> | null = null

// 搜索框控制
const toggleSearch = (show: boolean) => {
  showSearch.value = show
  if (!show) {
    searchQuery.value = ''
  }
}

// 搜索输入处理
const handleSearchInput = () => {
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
  
  searchTimeout = setTimeout(() => {
    
      const event = new CustomEvent('global-search', {
        detail: { 
          query: searchQuery.value.trim(),
          timestamp: Date.now()
        },
        bubbles: true,
        cancelable: true
      })
      window.dispatchEvent(event)

  }, 1000) // 3000毫秒延迟
}

// 搜索提交处理
const handleSearchSubmit = () => {
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
  
  if (searchQuery.value.trim()) {
    const event = new CustomEvent('global-search', {
      detail: { 
        query: searchQuery.value.trim(),
        timestamp: Date.now(),
        immediate: true
      },
      bubbles: true,
      cancelable: true
    })
    window.dispatchEvent(event)
  }
}

// 监听页面切换事件来控制搜索框显示
  onMounted(() => {
    const handlePageChange = (event: Event) => {
      const customEvent = event as CustomEvent
      const { showSearch: shouldShow } = customEvent.detail || {}
      toggleSearch(shouldShow || false)
    }
    
    window.addEventListener('page-search-toggle', handlePageChange as EventListener)
    
    // 只在用户已登录时显示搜索框（避免登录/注册页面显示）
    if (isLoggedIn.value) {
      setTimeout(() => {
        toggleSearch(true)
      }, 100)
    } else {
      toggleSearch(false) // 确保登录/注册页面不显示搜索框
    }
    
    // 清理监听器
    onUnmounted(() => {
      window.removeEventListener('page-search-toggle', handlePageChange as EventListener)
      if (searchTimeout) {
        clearTimeout(searchTimeout)
      }
    })
  })

// 下拉菜单控制
const toggleDropdown = () => {
  showDropdown.value = !showDropdown.value
}

// 点击外部关闭下拉菜单
const closeDropdown = () => {
  showDropdown.value = false
}

// 设置功能
const openSettings = () => {
  console.log('打开设置')
  closeDropdown()
  // 这里可以添加打开设置面板的逻辑
}

// 退出登录
const handleLogout = async () => {
  console.log('TitleBar: 用户点击退出登录')
  closeDropdown()
  
  try {
    // 使用 useAuth composable 的 logout 方法清理登录状态
    await logout()
    console.log('TitleBar: 登录状态已清理')
  } catch (error) {
    console.error('TitleBar: 退出登录失败', error)
    
    // 如果 useAuth 失败，作为备用方案触发事件
    const event = new CustomEvent('user-logout', { 
      detail: { timestamp: Date.now(), source: 'TitleBar' },
      bubbles: true,
      cancelable: true
    })
    window.dispatchEvent(event)
  }
}

// 监听点击外部关闭下拉菜单
const handleClickOutside = (e: MouseEvent) => {
  const target = e.target as HTMLElement
  if (!target.closest('.user-avatar')) {
    closeDropdown()
  }
}

// 添加和移除事件监听器
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.title-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 42px;
  background: var(--bg-header);
  border-bottom: 1px solid var(--border);
  padding: 0 16px;
  -webkit-app-region: drag;
  user-select: none;
  flex-shrink: 0;
  position: relative;
}

/* 左侧占位区域 */
.left-section {
  flex: 1;
  -webkit-app-region: drag;
}

/* 搜索框样式 */
.search-container {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 1000;
  -webkit-app-region: no-drag;
}

.search-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.search-input {
  width: 300px;
  height: 28px;
  padding: 0 32px 0 12px;
  border: 1px solid var(--border);
  border-radius: 14px;
  background: var(--bg-input);
  color: var(--text-primary);
  font-size: 13px;
  outline: none;
  transition: all 0.3s ease;
}

/* 响应式样式 */
@media (max-width: 1000px) {
  .search-input {
    width: 250px;
  }
}

@media (max-width: 800px) {
  .search-input {
    width: 200px;
  }
}

@media (max-width: 600px) {
  .search-input {
    width: 150px;
    font-size: 12px;
  }
}

.search-input:focus {
  border-color: var(--border-focus);
  background: var(--bg-tertiary);
  box-shadow: 0 0 0 2px var(--border-focus);
}

.search-input::placeholder {
  color: var(--text-muted);
}

.search-icon {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: var(--text-muted);
  pointer-events: none;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 8px;
  -webkit-app-region: drag;
  height: 100%;
}

.app-icon {
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-circle {
  width: 30px;
  height: 30px;
  background: var(--gradient-primary);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: var(--shadow-card);
  flex-shrink: 0;
}

.icon-music {
  font-size: 14px;
  filter: grayscale(1) brightness(2);
}

.app-title {
  height: 24px;
  color: var(--text-primary);
  font-size: 15px;
  font-weight: 600;
  margin: 0;
  letter-spacing: -0.3px;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 12px;
  -webkit-app-region: no-drag;
  flex: 1;
  justify-content: flex-end;
}

.user-section {
  display: flex;
  align-items: center;
  -webkit-app-region: no-drag;
}

.divider {
  width: 1px;
  height: 20px;
  background: var(--border);
  margin: 0 4px;
}

.user-avatar {
  position: relative;
  cursor: pointer;
  z-index: 10000;
}

.avatar-circle {
  width: 28px;
  height: 28px;
  background: var(--gradient-secondary);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  border: 1px solid var(--border);
}

.avatar-circle:hover {
  transform: scale(1.05);
  box-shadow: var(--shadow-hover);
}

.avatar-text {
  color: var(--text-inverse);
  font-size: 12px;
  font-weight: 600;
  user-select: none;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  margin-top: 8px;
  background: var(--bg-card);
  backdrop-filter: blur(20px);
  border: 1px solid var(--border);
  border-radius: 8px;
  box-shadow: var(--shadow-card);
  min-width: 120px;
  z-index: 9999;
  overflow: hidden;
}

.dropdown-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
  color: var(--text-primary);
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s ease;
  white-space: nowrap;
}

.dropdown-item:hover {
  background: var(--bg-tertiary);
}

.dropdown-icon {
  font-size: 14px;
}

/* 主题切换容器 */
.theme-toggle-container {
  margin-right: 12px;
  -webkit-app-region: no-drag;
}

.window-controls {
  display: flex;
  align-items: center;
  gap: 6px;
  -webkit-app-region: no-drag;
}

.control-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 26px;
  border: none;
  background: transparent;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
  color: var(--text-muted);
  -webkit-app-region: no-drag;
}

.control-btn:hover {
  background: var(--bg-tertiary);
  color: var(--text-primary);
}

.control-btn.minimize:hover {
  background: var(--bg-tertiary);
  color: var(--text-primary);
}

.control-btn.maximize:hover {
  background: var(--bg-tertiary);
  color: var(--text-primary);
}

.control-btn.close:hover {
  background: var(--accent-danger);
  color: var(--text-inverse);
}

.control-btn svg {
  width: 12px;
  height: 12px;
}

.control-btn.close svg {
  width: 10px;
  height: 10px;
}
</style>